package cn.wolfcode.wolf2w.listener;


import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    //spring容器初始化完毕执行该方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        //获取需要初始化的数据,攻略vo统计数据,用户攻略收藏列表
        //查询出攻略列表
        List<Strategy> strategies = strategyService.findAll();
        //遍历攻略列表,将数据塞到vo对象中去
        for (Strategy strategy : strategies) {
            //根据攻略sid查询redis是否存在该key
            if(strategyStatisVORedisService.isStrategyStatisVOExist(strategy.getId())){
                //存在则跳过该循环
                continue;
            }
            //否则将数据库的数据塞到vo对象中去
            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());
            //设置到redis中
            strategyStatisVORedisService.setStrategyStatisVO(vo);
        }

        //查询所有的用户
        List<UserInfo> users = userInfoService.listAll();
        for (UserInfo user : users) {
            if(userInfoRedisService.isUserStrategyFavorListExist(user.getId())){
                continue;
            }
            userInfoRedisService.setUserStrategyFavorList(user,user.getFavorStrategyList());
        }
    }


}
